"""
Pytest configuration and shared fixtures
"""
import pytest
import sys
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Base


@pytest.fixture(scope="function")
def db_session():
    """
    Create an in-memory SQLite database for each test
    """
    # Create in-memory database
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )

    # Create all tables
    Base.metadata.create_all(bind=engine)

    # Create session
    TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    session = TestingSessionLocal()

    try:
        yield session
    finally:
        session.close()
        # Drop all tables
        Base.metadata.drop_all(bind=engine)


@pytest.fixture
def sample_experiment_template_data():
    """Sample experiment template data for testing"""
    return {
        "name": "测试实验模板",
        "description": "用于单元测试的实验模板",
        "template_yaml": """name: 测试实验
desc: 测试实验描述
jobKind: job
tags:
  - test
  - unit
config:
  logUrl: /logs/test
  trainUrl: /output/test
  params:
    - key: batch_size
      value: "32"
      paramType: common
    - key: learning_rate
      value: "0.001"
      paramType: common
""",
        "created_by": "test_user"
    }


@pytest.fixture
def sample_workflow_definition():
    """Sample workflow definition for testing"""
    return {
        "nodes": [
            {
                "id": "node1",
                "type": "create_experiment",
                "name": "创建实验",
                "config": {
                    "template_id": 1,
                    "experiment_name": "test_experiment"
                },
                "next": "node2"
            },
            {
                "id": "node2",
                "type": "wait_completion",
                "name": "等待完成",
                "config": {
                    "timeout": 3600
                },
                "next": None
            }
        ]
    }


@pytest.fixture
def sample_workflow_data(sample_workflow_definition):
    """Sample workflow data for testing"""
    return {
        "name": "测试工作流",
        "description": "用于单元测试的工作流",
        "workflow_definition": sample_workflow_definition,
        "created_by": "test_user"
    }
